package com.example.abe.diandi.trends.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.example.BindView;
import com.example.OnClick;
import com.example.abe.diandi.R;
import com.example.abe.diandi.trends.model.ImageTextModel;

import example.abe.com.framework.imageloader.ImageLoader;
import example.abe.com.framework.viewinject.ViewInjectUtils;

public class TrendsEditImageView extends FrameLayout {

    @BindView(R.id.view_trend_edit_image_iv_photo)
    protected ImageView mIvPhoto;

    @BindView(R.id.view_trend_edit_image_iv_photo_et_content)
    protected EditText mEtContent;

    private Context mContext;

    private OnEditImageListener mListener;

    private ImageTextModel mImageTextModel;

    public TrendsEditImageView(Context context, int position) {
        super(context);
        init(context, position);
    }

    private void init(Context context, int position){
        mContext = context;
        View root = LayoutInflater.from(mContext).inflate(R.layout.view_trends_edit_image, this, false);
        ViewInjectUtils.inject(this, root);
        addView(root);

        mImageTextModel = new ImageTextModel();
        mImageTextModel.setPosition(position);

        mEtContent.addTextChangedListener(mEtWatcher);
    }

    public void setImage(String imgPath){
        mImageTextModel.setImage(imgPath);
        ImageLoader.getInstance().getImage(mIvPhoto, imgPath);
    }

    public void setEditImageListener(OnEditImageListener listener) {
        mListener = listener;
    }

    TextWatcher mEtWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mImageTextModel.setContent(mEtContent.getText().toString());
            if (mListener != null){
                mListener.afterTextChanged(mImageTextModel);
            }
        }
    };

    @OnClick(R.id.view_trend_edit_image_iv_delete)
    protected void onImageDeleteClick(){
        if (mListener != null){
            mListener.deleteEditImage(mImageTextModel);
        }
    }

    public interface OnEditImageListener {
        /**
         * 编辑完成回调
         * @param imageTextModel 图文数据
         */
        void afterTextChanged(ImageTextModel imageTextModel);

        /**
         * 删除此图文模块
         */
        void deleteEditImage(ImageTextModel model);
    }
}